//
//  ServiceContentViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/24.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"

#import "CommonServiceModel.h"

#import "DetailServiceContentCell.h"
#import "DetailServiceContentSectionHeader.h"

#import "ServiceContentViewController.h"

@interface ServiceContentViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate>

@property (nonatomic, strong) CommonServiceContentModel *serModel;

@property (nonatomic, strong) NSMutableDictionary *jsonDic;

@property (nonatomic, strong) NSMutableArray <CommonServiceModel *>* dataArray;

@property (nonatomic, assign) NSInteger lastcontentOffset; //添加此属性的作用，根据差值，判断ScrollView是上滑还是下拉

@end

@implementation ServiceContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareData1];
}
- (NSString *)handleStr:(NSString *)jsonString
{
    //1.替换{}->[]
    NSMutableString *string = [NSMutableString string];
    for (NSInteger index = 0; index < jsonString.length; index ++) {
        NSString *itemStr = [jsonString substringWithRange:NSMakeRange(index, 1)];
        if (index == 0 || index == jsonString.length - 1) {
            [string appendString:itemStr];
            continue;
        }
        if ([itemStr isEqualToString:@"{"]) {
            itemStr = @"[";
        }
        if ([itemStr isEqualToString:@"}"]) {
            itemStr = @"]";
        }
        [string appendString:itemStr];
    }
    //2.正则匹配出[] 并处理[]数据
    NSString *regex_emoji = @"\\[.*?\\]";
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:regex_emoji options:NSRegularExpressionCaseInsensitive error:nil];
    if (re) {
        NSArray *resultArray = [re matchesInString:string options:0 range:NSMakeRange(0, string.length)];
        for (NSInteger index = resultArray.count - 1; index >= 0; index --) {
            NSTextCheckingResult *match = resultArray[index];
            NSRange range = [match range];
            NSString *subStr = [string substringWithRange:range];
            [string replaceCharactersInRange:range withString:[self handleSubStr:subStr]];
        }
        //NSLog(@"%@",string);
    }
    //转json
    //NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    //NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    //NSLog(@"%@",string)
    //NSLog(@"%@",json)
    return string;
}
- (NSString *)handleSubStr:(NSString *)subStr
{
    //NSLog(@"subStr:%@",subStr);
    NSMutableString *string = [NSMutableString string];
    subStr = [subStr substringWithRange:NSMakeRange(1, subStr.length - 2)];
    //NSLog(@"subStr:%@",subStr);
    NSArray *array = [subStr componentsSeparatedByString:@","];
    [string appendString:@"["];
    for (NSInteger index = 0; index < array.count; index ++) {
        index == array.count - 1 ? [string appendString:[NSString stringWithFormat:@"{%@}",array[index]]] : [string appendString:[NSString stringWithFormat:@"{%@},",array[index]]];
    }
    [string appendString:@"]"];
    //NSLog(@"string:%@",string);
    //return @"😄";
    return string;
}
- (void)prepareData1
{
    self.serModel = [[CommonServiceContentModel alloc] init];
    self.serModel = self.model.sellerGoodsServiceFlag;
    NSString *jsonString = self.serModel.sgsServiceParameter;
    NSData *data = [[self handleStr:jsonString] dataUsingEncoding:NSUTF8StringEncoding];
    NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if (json == nil) {
        [self prepareData];
        return;
    }
    
    self.jsonDic = json.mutableCopy;
    
    NSArray *sectionTitles = self.jsonDic.allKeys;
    self.dataArray = @[].mutableCopy;
    for (int i = 0; i < sectionTitles.count; i++) {
        CommonServiceModel *sectionModel = [[CommonServiceModel alloc] init];
        sectionModel.itemTitle = sectionTitles[i];
        sectionModel.child = @[].mutableCopy;
        id obj = [self.jsonDic valueForKey:sectionTitles[i]];
        if ([obj isKindOfClass:[NSArray class]]) {
            NSArray *itemArray = (NSArray *)obj;
            for (NSInteger index = 0; index < itemArray.count; index ++) {
                id indexObj = itemArray[index];
                if ([indexObj isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *itemDic = (NSDictionary *)indexObj;
                    CommonServiceModel *cellModel = [[CommonServiceModel alloc] init];
                    cellModel.itemTitle = itemDic.allKeys.firstObject;
                    cellModel.itemContent = itemDic.allValues.firstObject;
                    //NSLog(@"%@ %@",cellModel.itemTitle,cellModel.itemContent);
                    cellModel.itemHeight = [Utilities getStringHeightWithText:cellModel.itemContent font:[UIFont systemFontOfSize:13] viewWidth:(TTScreenWidth - 153)] + 30;
                    if (cellModel.itemHeight < 50) {
                        cellModel.itemHeight = 50;
                    }
                    
                    if (cellModel.itemContent.length == 0) {
                        cellModel.itemHeight = CGFLOAT_MIN;
                    }
                    
                    [sectionModel.child addObject:cellModel];
                }
            }
        }
        [self.dataArray addObject:sectionModel];
    }
    [self initView];
}
- (void)prepareData {
    self.serModel = [[CommonServiceContentModel alloc] init];
    self.serModel = self.model.sellerGoodsServiceFlag;
    NSString *jsonString = self.serModel.sgsServiceParameter;
    //[self handleStr:jsonString];
    if (jsonString.length == 0) {
        return;
    }
    self.jsonDic = @{}.mutableCopy;
    self.jsonDic = [self convert2DictionaryWithJSONString:jsonString].mutableCopy;
    
    NSArray *sectionTitles = self.jsonDic.allKeys;
    self.dataArray = @[].mutableCopy;
    for (int i = 0; i < sectionTitles.count; i++) {
        CommonServiceModel *sectionModel = [[CommonServiceModel alloc] init];
        sectionModel.itemTitle = sectionTitles[i];
        sectionModel.child = @[].mutableCopy;
        NSDictionary *cellDic = [self.jsonDic valueForKey:sectionTitles[i]];
        NSArray *cellTitles = cellDic.allKeys;
        NSArray *cellContents = cellDic.allValues;
        
        for (int j = 0; j < cellTitles.count; j++) {
            CommonServiceModel *cellModel = [[CommonServiceModel alloc] init];
            if ([cellTitles[j] isKindOfClass:[NSString class]] && [cellContents[j] isKindOfClass:[NSString class]]) {
                cellModel.itemTitle = cellTitles[j];
                cellModel.itemContent = cellContents[j];
                cellModel.itemHeight = [Utilities getStringHeightWithText:cellModel.itemContent font:[UIFont systemFontOfSize:13] viewWidth:(TTScreenWidth - 153)] + 30;
                if (cellModel.itemHeight < 50) {
                    cellModel.itemHeight = 50;
                }
                [sectionModel.child addObject:cellModel];
            }
        }
        [self.dataArray addObject:sectionModel];
    }
    [self initView];
}

- (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"%@",err);
        return nil;
    }
    return dic;
}

- (void)initView {

    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.collectionView reloadData];
}


#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//    return self.jsonDic.allKeys.count;
    return self.dataArray.count;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
//    NSDictionary *dic = [self.jsonDic valueForKey:self.jsonDic.allKeys[section]];
    
    return self.dataArray[section].child.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        DetailServiceContentSectionHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DetailServiceContentSectionHeader" forIndexPath:indexPath];
        
        headerView.mainTitleLab.text = self.dataArray[indexPath.section].itemTitle;
        
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DetailServiceContentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DetailServiceContentCellID" forIndexPath:indexPath];
    
    cell.mainTitleLab.text = self.dataArray[indexPath.section].child[indexPath.row].itemTitle;
    cell.subTitleLab.text = self.dataArray[indexPath.section].child[indexPath.row].itemContent;

//    NSDictionary *dic = [self.jsonDic valueForKey:self.jsonDic.allKeys[indexPath.section]];
//
//    if (dic.allKeys.count > indexPath.row) {
//        NSString *title = dic.allKeys[indexPath.row];
//
//        if ([title isKindOfClass:[NSString class]]) {
//            cell.mainTitleLab.text = title;
//        }
//    }
//
//    if (dic.allValues.count > indexPath.row) {
//
//        NSString *content = dic.allValues[indexPath.row];
//        if ([content isKindOfClass:[NSString class]]) {
//            cell.subTitleLab.text = content;
//        }
//    }
    
    return cell;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高

    return self.dataArray[indexPath.section].child[indexPath.row].itemHeight;
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列

    return 1;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    return 0;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距

    return 0;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度

    return CGSizeMake(TTScreenWidth, 40);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return [UIColor whiteColor];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (!self.canScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    if (scrollView.contentOffset.y<=0) {
        self.canScroll = NO;
        scrollView.contentOffset = CGPointZero;
        [[NSNotificationCenter defaultCenter]postNotificationName:@"tabNoti" object:nil];
    }
    
    CGFloat hight = scrollView.frame.size.height;
    CGFloat contentOffset = scrollView.contentOffset.y;
    CGFloat distanceFromBottom = scrollView.contentSize.height - contentOffset;
    CGFloat offset = contentOffset - self.lastcontentOffset;
    self.lastcontentOffset = contentOffset;
    
    if (distanceFromBottom < hight) {
        if (offset > 0 && contentOffset > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"packageShowQuanYiNoti" object:nil userInfo:nil];
        }
    }
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
        //打开区头悬浮功能(默认关闭)
        layout.sectionHeadersPinToVisibleBounds = NO;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColorHex(0xf1f1f1);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
                
        [_collectionView registerNib:[UINib nibWithNibName:@"DetailServiceContentCell" bundle:nil] forCellWithReuseIdentifier:@"DetailServiceContentCellID"];
        
        [_collectionView registerNib:[UINib nibWithNibName:@"DetailServiceContentSectionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DetailServiceContentSectionHeader"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        WEAKSELF
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf.collectionView.mj_footer endRefreshing];
        }];
        
    }
    return _collectionView;
}

@end
